const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const mysql = require('promise-mysql')
const index = require('./routes/index')
const users = require('./routes/users')
const articles = require('./routes/articles')
const cors = require('kcors')
const security = require('./security')

// error handler
//onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(cors())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(security)


const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  // password: '', //password in MAc
  password:'123456', //password in my Windows 10
  database: 'blog',
  connectionLimit: 10
})

app.use(async (ctx, next) => {
  ctx.connection = await pool.getConnection()
  await next()
  ctx.connection.end()
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(articles.routes(), articles.allowedMethods())

app.listen(8080)
